package gemini.castor.ui.client.page.content.account.mysponsor.form;

import gemini.basic.model.Distributor;
import gemini.castor.ui.client.ServiceCatalog;
import gemini.castor.ui.client.mvp.callback.AbstractAsyncCallback;
import gemini.castor.ui.client.mvp.single.CastorWidgetDisplay;
import gemini.castor.ui.client.mvp.single.CastorWidgetPresenter;
import gemini.castor.ui.client.page.RootEvent;
import gemini.castor.ui.client.utils.GuiUtils;
import gemini.castor.ui.client.utils.PlaceConstants;
import ch.elca.gwt.mvp.client.EventBus;
import ch.elca.gwt.mvp.client.place.Place;

import com.google.inject.Inject;

public class MySponsorFormPresenter extends
		CastorWidgetPresenter<MySponsorFormPresenter.Display> {

	@Inject
	public MySponsorFormPresenter(Display display, EventBus globalEventBus) {
		super(display, globalEventBus);
	}

	public interface Display extends CastorWidgetDisplay {

		void setDistributorSponsor(Distributor distributor);
	}

	public static final Place PLACE = new Place(PlaceConstants.PLACE_MY_SPONSOR);
	
	private String distributorCode;
	
	@Override
	public void setInputObject(Object ob){
		distributorCode = (String) ob;
	}
	

	@Override
	protected void onBind() {
		eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.MASK));
		ServiceCatalog.getSponsorService().getSponsorByCode(distributorCode,
				new AbstractAsyncCallback<Distributor>() {

					@Override
					public void onSuccess(Distributor result) {
						eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.UN_MASK));
						if (result != null) {
							display.setDistributorSponsor(result);
							display.loadData();
						} else {
							GuiUtils.alert("Cannot find sponsor in database!");
						}
					}
				});
	}

	@Override
	public Place getPlace() {
		return PLACE;
	}
}
